package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.*;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.mapper.ArticleMapper;
import com.itheima.ydd.mapper.CateMapper;
import com.itheima.ydd.mapper.ConfigMapper;
import com.itheima.ydd.mapper.YddUserMapper;
import com.itheima.ydd.service.*;
import com.itheima.ydd.service.ConfigService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yan.zhou
 * @since 2022-02-21
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CateService cateService;
    @Autowired
    private AdvimgService advimgService;
    @Autowired
    private YddUserService yddUserService;
    @Autowired
    private LinkService linkService;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ConfigMapper configMapper;
    @Autowired
    private CateMapper cateMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private AdvposService advposService;
    @Autowired
    private YddUserMapper yddUserMapper;

    @Override
    public Map<String, Object> profile() {
        HashMap<String, Object> map = new HashMap<>();
        //1. 查询用户信息
        User user = userService.getById(UserHolder.getUserId());
        SysUserInfo userInfo = new SysUserInfo();
        BeanUtils.copyProperties(user, userInfo);
        //查询用户角色id集合: role_id
        String[] rowIds = user.getRole_id().replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        List<String> ids = new ArrayList<>();
        Collections.addAll(ids, rowIds);
        map.put("userInfo", userInfo);

        //查询用户角色名称集合: role_id
        String role_id = UserHolder.get().getRole_id();
        List<String> roleNameList = roleService.roleNameList(role_id);
        userInfo.setRolename(roleNameList);

        //2. 查询角色菜单集合
        List<Menu> menuList = menuService.menuList(role_id);
        map.put("menuList", menuList);


        //region #dictsList 不知道干嘛用的，结果直接为原本数据
        HashMap<String, Object> dictsList = new HashMap<>();
        HashMap<String, String> interface_type = new HashMap<>();
        interface_type.put("get", "get");
        interface_type.put("post", "post");
        dictsList.put("interface_type", interface_type);

        ArrayList<String> table_type = new ArrayList<>();
        table_type.add("单表");
        table_type.add("主表");
        table_type.add("附表");
        table_type.add("树结构表");
        dictsList.put("table_type", table_type);

        ArrayList<String> order_type = new ArrayList<>();
        order_type.add("支付宝");
        order_type.add("微信");
        dictsList.put("order_type", order_type);

        ArrayList<String> report_type = new ArrayList<>();
        report_type.add("正常报告");
        report_type.add("异常报告");
        dictsList.put("report_type", report_type);

        HashMap<String, String> theme = new HashMap<>();
        theme.put("ace", "ACE风格");
        dictsList.put("theme", theme);
        map.put("dictsList", dictsList);

        return map;
    }

    @Override
    public Map<String, Object> all() {
        Map<String, Object> map = new HashMap<>();
        List<Config> configs = configMapper.selectList(new LambdaQueryWrapper<Config>()
                .orderByAsc(Config::getSort_num));

        Map<String, String> configForm = new HashMap<>();
        Map<String, String> configRules = new HashMap<>();

        ConfigDto1 base = new ConfigDto1();     //基础配置
        ConfigDto1 system = new ConfigDto1();   //系统设置
        ConfigDto1 custom = new ConfigDto1();   //其他设置

        base.setKey("base");
        base.setName("基础配置");
        system.setKey("system");
        system.setName("系统设置");
        custom.setKey("custom");
        custom.setName("其他设置");

        List<ConfigDto2> baseArray = new ArrayList<>();
        List<ConfigDto2> systemArray = new ArrayList<>();
        List<ConfigDto2> customArray = new ArrayList<>();
        List<ConfigDto> dtoList = configs.stream().map((config) -> {
            ConfigDto dto = new ConfigDto();
            BeanUtils.copyProperties(config, dto);
            String config_value = config.getConfig_value();
            //处理
            List<Map<String, Object>> maps = doConfigValue(config_value, config.getType());
            dto.setConfig_value(maps);

            // 处理 configForm
            configForm.put(config.getAttr_key(), config.getAttr_value());

            // 处理configRules
            if (config.getValidator() != null && !"".equals(config.getValidator())) {
                configRules.put(config.getAttr_key(), config.getValidator());
            }


            if (Objects.equals(config.getTab_value(), "base")) {
                doConfigDto2Arr(baseArray, dto);
            }
            if (Objects.equals(config.getTab_value(), "system")) {
                doConfigDto2Arr(systemArray, dto);
            }
            if (Objects.equals(config.getTab_value(), "custom")) {
                doConfigDto2Arr(customArray, dto);
            }

            return dto;
        }).collect(Collectors.toList());

        base.setChildren(baseArray);
        system.setChildren(systemArray);
        custom.setChildren(customArray);
        List<ConfigDto1> allData = new ArrayList<>();

        Collections.addAll(allData, base, system, custom);

        map.put("allData", dtoList);
        map.put("configForm", configForm);
        map.put("configRules", configRules);
        map.put("list", allData);

        return map;
    }

    private List<ConfigDto2> doConfigDto2Arr(List<ConfigDto2> array, ConfigDto configDto) {
        String group_value = configDto.getGroup_value();
        boolean flag = true;
        for (ConfigDto2 configDto2 : array) {
            if (configDto2.getName().equals(group_value)) {
                configDto2.getData().add(configDto);
                flag = false;
            }
        }
        if (flag) {
            ConfigDto2 configDto2 = new ConfigDto2();
            configDto2.setName(group_value);
            List<ConfigDto> dataList = new ArrayList<>();
            dataList.add(configDto);
            configDto2.setData(dataList);
            array.add(configDto2);
        }
        return array;
    }

    /**
     * 获取主页统计参数
     *
     * @return
     */
    @Override
    public Map<String, Object> baseInfo() {
        Map<String, Object> map = new HashMap<>();
        List<CateInfo> allCate = cateMapper.getAllCate();
        map.put("all_cate", allCate);

        //广告位总数
        map.put("advpos_num", advposService.count(new QueryWrapper<Advpos>().select("default_data  is not null")));

        //标签总数
        map.put("tag_num", tagService.count());

        //管理员总数
        map.put("admin_num", userService.count());

        //文章总数
        map.put("article_num", articleService.count());

        //分类总数
        map.put("cate_num", cateService.count());

        //广告图总数
        map.put("advimg_num", advimgService.count());

        //最新用户数据
        LambdaQueryWrapper<YddUser> lqw = new LambdaQueryWrapper<>();
        List<YddUser> yddUser = yddUserMapper.selectList(lqw.orderByDesc(YddUser::getId).last("limit 7"));
        map.put("new_user", yddUser);

        //热门文章数据
        LambdaQueryWrapper<Article> lqw1 = new LambdaQueryWrapper<>();
        List<Article> article = articleMapper.selectList(lqw1.orderByDesc(Article::getClick).last("limit 7"));
        map.put("hot_article", article);

        //用户数据
        int count = yddUserService.count();
        QueryWrapper<YddUser> qw1 = new QueryWrapper<>();
        qw1.groupBy("sex");
        qw1.select("sex,count(sex) as num");
        List<YddUser> yddUsers = yddUserMapper.selectList(qw1);
        UserInfo userInfo = new UserInfo();
        userInfo.setTotal((long) count);
        for (YddUser user : yddUsers) {
            if (user.getSex() == 0) {
                userInfo.setUser_man(user.getNum());
            }
            if (user.getSex() == 1) {
                userInfo.setUser_woman(user.getNum());
            }
        }
        map.put("user", userInfo);
        return map;
    }

    /**
     * 首页和全局数据
     *
     * @return
     */
    @Override
    public ForwardDto getForwardDto() {

        //所有分类
        List<Cate> allCate = cateService.list();

        //所有友情链接
        List<Link> allLink = linkService.list();

        //所有标签
        List<Tag> allTag = tagService.list();

        //前台配置
        List<Config> allData = this.list(new LambdaQueryWrapper<Config>().select(
                Config::getAttr_key,
                Config::getAttr_value,
                Config::getConfig_value,
                Config::getId,
                Config::getType,
                Config::getValidator
        ).orderByAsc(Config::getSort_num));
        ConfigDto1 base = new ConfigDto1();     //基础配置
        ConfigDto1 system = new ConfigDto1();   //系统设置
        ConfigDto1 custom = new ConfigDto1();   //其他设置

        base.setKey("base");
        base.setName("基础配置");
        system.setKey("system");
        system.setName("系统设置");
        custom.setKey("custom");
        custom.setName("其他设置");

        List<ConfigDto2> baseArray = new ArrayList<>();
        List<ConfigDto2> systemArray = new ArrayList<>();
        List<ConfigDto2> customArray = new ArrayList<>();


        allData.forEach((config) -> {
            ConfigDto dto = new ConfigDto();
            BeanUtils.copyProperties(config, dto);
            //处理
            List<Map<String, Object>> maps = doConfigValue(config.getConfig_value(), config.getType());
            dto.setConfig_value(maps);
            if (Objects.equals(config.getTab_value(), "base")) {
                doConfigDto2Arr(baseArray, dto);
            }
            if (Objects.equals(config.getTab_value(), "system")) {
                doConfigDto2Arr(systemArray, dto);
            }
            if (Objects.equals(config.getTab_value(), "custom")) {
                doConfigDto2Arr(customArray, dto);
            }
        });
        base.setChildren(baseArray);
        system.setChildren(systemArray);
        custom.setChildren(customArray);
        List<ConfigDto1> list = new ArrayList<>();
        Collections.addAll(list, base, system, custom);

        //轮播图数据、侧边栏图片、详情广告图
        List<Advimg> advimgs = advimgService.list(new LambdaQueryWrapper<Advimg>().select(
                Advimg::getAdvimgdesc,
                Advimg::getAdvimglink,
                Advimg::getAdvimgsrc,
                Advimg::getAdvimgpos,
                Advimg::getId
        ));
        List<Advimg> banner = new ArrayList<>();
        List<Advimg> showBanner = new ArrayList<>();
        List<Advimg> sideBanner = new ArrayList<>();
        advimgs.forEach(item -> {
            switch (item.getAdvimgpos()) {
                case "15":
                    banner.add(item);
                    break;
                case "13":
                    showBanner.add(item);
                    break;
                case "14":
                    sideBanner.add(item);
                    break;
            }
        });
        ForwardDto forwardDto = new ForwardDto();
        forwardDto.setAllCate(allCate);
        forwardDto.setAllLink(allLink);
        forwardDto.setAllTag(allTag);
        HashMap<String, Object> config = new HashMap<String, Object>();
        config.put("allData", allData);
        config.put("list", list);
        forwardDto.setConfig(config);
        forwardDto.setBanner(banner);
        forwardDto.setShowBanner(showBanner);
        forwardDto.setSideBanner(sideBanner);
        return forwardDto;
    }

    /***
     * Desc:处理 ConfigValue
     * @param
     * @return {@link List< Map< String, Object>>}
     * @author Cr Mr
     * @date 2022/3/3 20:40
     */

    public List doConfigValue(String config_value, Integer type) {
        if (!"".equals(config_value)) {
            if (type == 4) {
                String[] rules = config_value.split("&");
                List configValue = new ArrayList<>();
                for (String rule : rules) {
                    String[] split = rule.split("=");
                    Map<String, Object> ruleHashMap = new HashMap<>();
                    ruleHashMap.put("label", split[0]);
                    ruleHashMap.put("value", split[1]);

                    configValue.add(ruleHashMap);
                }

                return configValue;
            }
        }

        return null;
    }

}
